<?php
/**
 * Copyright (c) 2006-2008, Julien PORTALIER
 * http://featherphp.googlecode.com/
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 */

/**
 * Interface for cookies.
 */
class Cookies
{
	/**
	 * Cookie exists?
	 * 
	 * @param  $key    String  Cookie name.
	 * @return Boolean Exists? 
	 */
	function check($key)
	{
		return isset($_COOKIE[$key]);
	}
	
	/**
	 * Gets a cookie value (if exists).
	 *
	 * The value may be any PHP variable (integer, string, array, etc).
	 * 
	 * @param  $key String  Cookie name.
	 * @return mixed $data  Cookie value, null otherwise.
	 */
	function read($key)
	{
		return Cookies::check($key) ? unserialize(base64_decode($_COOKIE[$key])) : null;
#		return Cookies::check($key) ? json_decode($_COOKIE[$key], true) : null;
	}
	
	/**
	 * Creates a cookie.
	 * 
	 * The value may be any PHP variable type (integer, string, array, etc).

	 * @param  $key    String  Cookie name.
	 * @param  $value  mixed   Value to store in cookie.
	 * @param  $expire mixed   Expiration date -- parseable by strtotime.
	 * @param  $path   String  Path.
	 * @param  $domain String  Domain.
	 * @param  $secure boolean SSL?
	 * @return boolean Success?
	 */
	function write($key, $value, $expire='+1 month', $path='/', $domain=null, $secure=false)
	{
		if (is_string($expire))
			$expire = strtotime($expire);
		if (is_null($domain))
			$domain = Core::session_domain;
		$value = base64_encode(serialize($value));
#		$value = json_encode($value);
		return setcookie($key, $value, $expire, $path, $domain, $secure);
	}
	
	/**
	 * Deletes a cookie.
	 * 
	 * @param  $key    String  Cookie name.
	 * @return boolean Success?
	 */
	function delete($key)
	{
		return Cookies::write($key, '', '-1 month');
	}
}
?>